package com.dc.datacollect.exception;

import com.dc.datacollect.conduit.R;
import com.dc.datacollect.conduit.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
@Slf4j
@RestControllerAdvice
public class GlobalExceptionControllerAdvice {
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R handleValidException(MethodArgumentNotValidException e) {
        log.error("数据校验出现问题{}，异常类型：{}",e.getMessage(),e.getClass());
        HashMap<String, String> errMap = new HashMap<>(8);
        e.getBindingResult().getFieldErrors().forEach(item->{

            String field = item.getField();
            String message = item.getDefaultMessage();
            if(errMap.get(field) != null) {
                // 之前已经存在，追加信息
                message = errMap.get(field) +  ("," +message);
            }
            errMap.put(field,message);
        });
        return R.error(ResultCode.PARAM_ERROR).data(errMap);
    }
    @ExceptionHandler(Exception.class)
    public R allException(Exception e) {
        log.error("出现问题{}，异常类型：{}",e.getMessage(),e.getClass());
        return R.error(ResultCode.FAIL.getCode(),e.getMessage());
    }

}